<?php

namespace app\common\model;

class PatientRecord extends BaseModel
{
    protected $name = "patient_record";

    protected $type = [
        'patientId'  => 'string',
        'type'       => 'integer',
        'created_at' => 'integer',
        'updated_at' => 'integer',
    ];

    /**
     * 获取数据列表
     */
    public function getLists($type)
    {
        $field = '*';
        switch ($type){
            case 1:
                $field = "id,patientId,clinicNo,patientName,patientSex,patientBirth,patientMobile,attendingDoctorName,visitTime,deptName,diagnosis";
        }
        return $this->where('type', $type)
                ->field($field)
                ->order('visitTime', 'desc')
               // ->limit(1)
                ->paginate($this->pageLimit);
    }

    /**
     * 添加数据
     * @param array $data
     * @return string
     */
    public function addData(array $data): string
    {
        //添加时销毁自带的主键id
        unset($data['id']);
        return $this->save($data);
    }

    /**
     * 更新数据
     * @param array $data
     * @return bool
     */
    public function saveData($id, array $data): bool
    {
        $model = self::find($id);
        return $model->save($data);
    }

    /**
     * 根据患者ID,type获取对应数据
     */
    public function getWhereType($patientId, $type, $field = "*", $order)
    {
        $where['type'] = $type;
        $where['patientId'] = $patientId;
        
        return $this->field($field)
                ->where($where)
                ->order($order, 'desc')
                ->select()
                ->each(function($item, $key){
                    isset($item['visitTime'])&&!empty($item['visitTime'])?$item['visitTime'] = date('Y-m-d', strtotime($item['visitTime'])):'';

                    if (isset($item['inhospitalDate'])&&!empty($item['inhospitalDate']))
                    {
                        $item['inhospitalDate'] = date('Y-m-d', strtotime($item['inhospitalDate']));
                    }

                    if (isset($item['outhospitalDate'])&&!empty($item['outhospitalDate']))
                    {
                        $item['outhospitalDate'] = date('Y-m-d', strtotime($item['outhospitalDate']));
                    }
                    return $item;
                })
                ->toArray();
    }

    /**
     * 根据患者ID,type统计对应数据
     */
    public function getTypeCount($patientId, $type)
    {
        $where['type'] = $type;
        $where['patientId'] = $patientId;

        return $this->where($where)->count();
    }

    /**
     * 根据主键id获取对应数据
     */
    public function getWhereId($id, $field = "*")
    {
        return $this->field($field)->where('id', $id)->find();
    }

    /**
     * 根据患者id获取对应数据
     */
    public function getWherePatientId($patientId)
    {
        $field = 'id,type,visitTime,deptName,inhospitalDate,outhospitalDate,inhospitalDeptCode,outhospitalDeptCode';
        $list = $this->where('patientId', $patientId)->field($field)->select()->toArray();

        if ($list)
        {
            $times = [];
            $ids = [];
            foreach ($list as $key => $val)
            {
                switch ($val['type'])
                {
                    case 1:
                        $time = date('Y-m-d', strtotime($val['visitTime']));
                        $times[$val['id']] = $time;
                        $ids[$time] = $val['id'];
                        break;
                    case 2:
                        $time = substr($val['inhospitalDate'], 0, strrpos($val['inhospitalDate'],'T'));
                        $times[$val['id']] = date('Y-m-d', strtotime($time));
                        $ids[date('Y-m-d', strtotime($time))] = $val['id'];
                        break;
                    case 3:    
                        $time = substr($val['outhospitalDate'], 0, strrpos($val['outhospitalDate'],'T'));
                        $times[$val['id']] = date('Y-m-d', strtotime($time));
                        $ids[date('Y-m-d', strtotime($time))] = $val['id'];
                        break;
                }
            }

            $newest = max($times);
            $id = $ids[$newest];

            $row = $this->where('id', $id)->field($field)->find();
            switch ($row['type'])
            {
                case 1:
                    $data['id'] = $row['id'];
                    $data['type'] = '门诊';
                    $data['time'] = date('Y-m-d', strtotime($row['visitTime']));
                    $data['department'] = $row['deptName'];
                    break;
                case 2:
                    $data['id'] = $row['id'];
                    $data['type'] = '住院';
                    $originalTime = substr($row['inhospitalDate'], 0, strrpos($row['inhospitalDate'],'T'));
                    $data['time'] = date('Y-m-d', strtotime($originalTime));
                    $data['department'] = $row['inhospitalDeptCode'];
                    break;
                case 3:    
                    $data['id'] = $row['id'];
                    $data['type'] = '出院';
                    $originalTime = substr($row['outhospitalDate'], 0, strrpos($row['outhospitalDate'],'T'));
                    $data['time'] = date('Y-m-d', strtotime($originalTime));
                    $data['department'] = $row['outhospitalDeptCode'];
                    break;
            }
            return $data;
        }else{
            return [];
        }
    }

    /**
     * 病历详情
     */
    public function getRecordDetail($id)
    {
        $row = $this->where('id', $id)->find();

        $data['id'] = $row['id'];

        switch ($row['type'])
        {
            case 1:
                $data['type'] = '门诊';
                $data['time'] = date('Y-m-d', strtotime($row['visitTime']));
                $data['department'] = $row['deptName'];
                $data['doctor'] = $row['attendingDoctorName'];
                $data['image'] = $row['images'];
                break;
            case 2:
                $data['type'] = '住院';
                $data['time'] = date('Y-m-d', strtotime($row['inhospitalDate']));
                $data['department'] = $row['inhospitalDept'];
                $data['doctor'] = $row['inchargeDoctorName'];
                $data['image'] = $row['images'];
                break;
            case 3:    
                $data['type'] = '出院';
                $data['time'] = date('Y-m-d', strtotime($row['outhospitalDate']));
                $data['department'] = $row['outhospitalDept'];
                $data['doctor'] = $row['inchargeDoctorName'];
                $data['image'] = $row['images'];
                break;
        }
        return $data;
    }

    /**
     * 病历统计
     */
    public function getRecordStatistics($patientId)
    {
        $data['totalNum'] = $this->where(['patientId' => $patientId])->count();

        $outlist = $this->where(['patientId' => $patientId, 'type' => 1])->field('id,visitTime')->select()->toArray();
        $inlist = $this->where(['patientId' => $patientId, 'type' => 2])->field('id,inhospitalDate')->select()->toArray();

        $outdata = [];
        foreach ($outlist as $key => $val)
        {
            $visitTime = substr($val['visitTime'], 0, 4);
        
            if ($visitTime == date('Y'))
            {
                $outdata[] = $val;
            } 
        }

        $indata = [];
        foreach ($inlist as $key => $val)
        {
            $inhospitalDate = substr($val['inhospitalDate'], 0, 4);
            
            if ($inhospitalDate == date('Y'))
            {
                $indata[] = $val;
            } 
        }
        
        $data['outNum'] = count($outdata);
        $data['inNum'] = count($indata);
        return $data;
    }

    /**
     * 根据患者id获取全部数据
     */
    public function getPatientIdDatas($patientId, $type)
    {
        switch ($type)
        {
            case 1:
                $data = $this->where(['patientId' => $patientId, 'type' => 1])
                        ->whereLike('visitTime', date('Y'))
                        ->field('id,visitTime,diseaseName')
                        ->order('visitTime', 'desc')
                        ->paginate($this->pageLimit)
                        ->each(function($item, $key){
                            $item['time'] = date('Y-m-d', strtotime($item['visitTime']));
                            $item['diagnosis'] = $item['diseaseName'];
                            return $item;
                        });      
                break;
            case 2:
                $data = $this->where(['patientId' => $patientId, 'type' => 2])
                        ->whereLike('inhospitalDate', date('Y'))
                        ->field('id,inhospitalDate,diagnose')
                        ->order('inhospitalDate', 'desc')
                        ->paginate($this->pageLimit)
                        ->each(function($item, $key){
                            $item['time'] = date('Y-m-d', strtotime($item['inhospitalDate']));
                            $item['diagnosis'] = $item['diagnose'];
                            return $item;
                        });
                break; 
            default:
                $data = $this->where(['patientId' => $patientId])
                            ->field('id,type,visitTime,diagnosis,inhospitalDate,outhospitalDate,diagnose,diseaseName')
                            ->select()
                            ->each(function($item, $key){
                                switch ($item['type'])
                                {
                                    case 1:
                                        $item['time'] = date('Y-m-d', strtotime($item['visitTime']));
                                        $item['diagnosis'] = $item['diseaseName'];
                                        break;
                                    case 2:
                                        $item['time'] = date('Y-m-d', strtotime($item['inhospitalDate']));
                                        $item['diagnosis'] = $item['diagnose'];       
                                        break; 
                                    case 3:
                                        $item['time'] = date('Y-m-d', strtotime($item['outhospitalDate']));
                                        $item['diagnosis'] = $item['diagnose'];
                                        break;       
                                }
                                return $item;
                            })
                            ->toArray();
                $sort = array_column($data, 'time');
                array_multisort($sort, SORT_DESC, $data);  
        }
        return $data;
    }

    /**
     * 删除图片
     *
     */
    public function delImage($id, int $key)
    {
        $image = $this->where('id', $id)->field('images')->find();
        
        if (isset($image['images']) && !empty($image['images']))
        {
            $images = $image->toArray();
            unset($images['images'][$key]);
            $data = [];
            foreach ($images['images'] as $k => $v)
            {
                $data['images'][] = $v;
            }
            return $this->saveData($id, $data);
        }
        return false;
    }
}   
